package top.kaoshanji.ch06;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import top.kaoshanji.ch06.serviceLoader.Cipher;

import java.nio.charset.StandardCharsets;
import java.util.ServiceLoader;

/**
 * 代码清单 ch06-02：服务加载器示例(6.4节)
 * author kaoshanji
 * ^_^
 * create time 2024/11/27 15:28
 */
public class ServiceLoaderTest {

    private static final Logger logger = LogManager.getLogger(ServiceLoaderTest.class);

    public static ServiceLoader<Cipher> cipherServiceLoader = ServiceLoader.load(Cipher.class);

    public static void main(String[] args) {
        logger.info("...代码清单 ch06-02：服务加载器示例(6.4节)...");

        Cipher cipher = getCipher(1);
        var message = "Meet me at the toga party.";
        byte[] bytes = cipher.encrypt(message.getBytes(), new byte[] { 3 });
        var encrypted = new String(bytes, StandardCharsets.UTF_8);
        System.out.println(encrypted);

    }

    public static Cipher getCipher(int minStrength) {
        for (Cipher cipher: cipherServiceLoader) {
            if (cipher.strength() >= minStrength) {
                return cipher;
            }
        }

        return null;
    }

}
